package me.spring.cloud.components.starter.oauth2.backend.configuration;

import me.spring.cloud.common.components.oauth2.exception.CustomerWebResponseExceptionTranslator;
import me.spring.cloud.common.components.oauth2.integration.IntegrationAuthenticationFilter;
import me.spring.cloud.common.components.oauth2.token.store.RedisTokenStore;
import me.spring.cloud.components.starter.oauth2.backend.handler.Oauth2LogoutHandler;
import me.spring.cloud.components.starter.oauth2.backend.handler.Oauth2LogoutSuccessHandler;
import me.spring.cloud.components.starter.oauth2.backend.properties.JwtTokenProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.util.Assert;

/**
 * @author: luffy
 * @create: 2018-09-11 09:46
 **/
@Configuration
@Import({WebSecurityAccessConfiguration.class, ResourceServerConfiguration.class})
public class Oauth2CenterConfiguration {

  @Autowired
  private RedisConnectionFactory redisConnectionFactory;

  @Autowired
  private JwtTokenProperties jwtTokenProperties;

  @Bean
  public WebResponseExceptionTranslator webResponseExceptionTranslator() {
    return new CustomerWebResponseExceptionTranslator();
  }

  @Bean
  public IntegrationAuthenticationFilter integrationAuthenticationFilter() {
    return new IntegrationAuthenticationFilter();
  }

  @Bean
  public LogoutHandler logoutHandler() {
    return new Oauth2LogoutHandler();
  }

  @Bean
  public LogoutSuccessHandler logoutSuccessHandler() {
    return new Oauth2LogoutSuccessHandler();
  }

  @Bean
  public TokenStore redisTokenStore() {
    Assert.notNull(redisConnectionFactory, "redisConnectionFactory must be set");
    return new RedisTokenStore(redisConnectionFactory);
  }

  @Bean
  public JwtAccessTokenConverter jwtAccessTokenConverter() {
    Assert.notNull(jwtTokenProperties, "jwtTokenProperties must be set");
    Assert.notNull(jwtTokenProperties.getTokenSign(), "properties jwt token sign must be set");
    JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
    accessTokenConverter.setSigningKey(jwtTokenProperties.getTokenSign());
    return accessTokenConverter;
  }
}
